package net.zhengxinyun.performance.controller.exam;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.data.SelectOptionBean;
import net.zhengxinyun.performance.entity.ExamIndex;
import net.zhengxinyun.performance.entity.ExamQuestionEntity;
import net.zhengxinyun.performance.entity.TokenEntity;
import net.zhengxinyun.performance.filter.ExamQuestionFilter;
import net.zhengxinyun.performance.filter.SelectionFilter;
import net.zhengxinyun.performance.service.exam.exam.ExamService;
import net.zhengxinyun.performance.service.exam.examClass.ExamIndexService;
import net.zhengxinyun.performance.service.exam.select.OptionClasService;
import net.zhengxinyun.performance.service.exam.select.SelectionService;
import net.zhengxinyun.performance.service.exportService.ExportService;
import net.zhengxinyun.performance.service.login.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问卷问题
 */
@RestController
@RequestMapping("/examQuestion")
public class ExamQuestionCtrl {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ExamIndexService  examIndexService;//问卷分类
    @Autowired
    private ExamService examService; //问卷试题
    @Autowired
    private OptionClasService OptionClassService;//问卷选项分类
    @Autowired
    private SelectionService selectionService;//问卷选项

    @Autowired
    private ExportService excelService;

    @PostMapping("/query")
    public Result<HashMap<String,Object>> query(@RequestBody QuestionParam param)
    {

        if(tokenService.compareToken(param.tokenEntity.getValue()))
        {
            HashMap<String,Object> map = new HashMap<>();

            List<ExamQuestionFilter> query = examService.query(param.filter);
            if(query.size()==0)
            {
                param.filter.setPageNumber(param.filter.getPageNumber()-1);
                query =examService.query(param.filter);
            }
            int total = examService.queryForCount(param.filter);
            map.put("list",query);
            map.put("pageTotal",total);

            return ResultUtils.getSuccessResults(map);
        }
        return  ResultUtils.getResults(Result.Status.OVERTIME,"error token",null);
    }

    /**
     * 生成问卷
     * @param param
     * @return
     */
    @PostMapping("/insert")
    public  Result<String> insertExamIndex(@RequestBody QuestionParam param)
    {
        if(tokenService.compareToken(param.tokenEntity.getValue())) {
            List<SelectionFilter> selectList = new ArrayList<>();
            List<ExamQuestionEntity> examList = param.entity.getExamList();
            Long examId = param.entity.getExamId();
            Long optionId = param.entity.getOptionId();
         /*   ExamQuestionFilter exfilter = new ExamQuestionFilter();
            exfilter.setExamId(examId);
            List<ExamQuestionFilter> query = examService.query(exfilter);
            if (ObjectUtils.isNotBlank(query)) {
                int code = examService.insertLog(query);
                if (code == 0) {
                    System.out.println("保存失败");
                }

                examService.deleteByPrimaryKey(examId);
            }*/
            deleteRepeat(examId);

            /**
             * 选项值
             */
            SelectionFilter filter = new SelectionFilter();
            filter.setOptionId(optionId);
            selectList= selectionService.query(filter);






            for (int i = 0; i < examList.size(); i++) {
                ExamQuestionEntity entity = examList.get(i);
                entity.setSort(i + 1);
                entity.setExamId(examId);
                entity.setOptionId(optionId);

            /* 设置题干 */
                setSelecctValue(entity,selectList);

                examService.saveExam(entity);
            }


            return ResultUtils.getResults(Result.Status.SUCCESS, "操作成功");
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "登录过期");
    }

    /**
     * 设置题干
     * @param entity
     * @param list
     */
    private void  setSelecctValue(ExamQuestionEntity entity , List<SelectionFilter> list ){

        /*
            A
         */
        try {
            entity.setSelectA(list.get(0).getOptions());

        }catch (IndexOutOfBoundsException e){
            entity.setSelectA(null);
        }

        try {
            entity.setWeightA(list.get(0).getWeight());

        }catch (IndexOutOfBoundsException e){
            entity.setWeightA(0);
        }


         /*
            B
         */
        try {
            entity.setSelectB(list.get(1).getOptions());

        }catch (IndexOutOfBoundsException e){
            entity.setSelectB(null);
        }

        try {
            entity.setWeightB(list.get(1).getWeight());

        }catch (IndexOutOfBoundsException e){
            entity.setWeightB(0);
        }

        /*
            C
         */
        try {
            entity.setSelectC(list.get(2).getOptions());

        }catch (IndexOutOfBoundsException e){
            entity.setSelectC(null);
        }

        try {
            entity.setWeightC(list.get(2).getWeight());

        }catch (IndexOutOfBoundsException e){
            entity.setWeightC(0);
        }


         /*
            D
         */
        try {
            entity.setSelectD(list.get(3).getOptions());

        }catch (IndexOutOfBoundsException e){
            entity.setSelectD(null);
        }

        try {
            entity.setWeightD(list.get(3).getWeight());

        }catch (IndexOutOfBoundsException e){
            entity.setWeightD(0);
        }


         /*
            E
         */
        try {
            entity.setSelectE(list.get(4).getOptions());

        }catch (IndexOutOfBoundsException e){
            entity.setSelectE(null);
        }

        try {
            entity.setWeightE(list.get(4).getWeight());

        }catch (IndexOutOfBoundsException e){
            entity.setWeightE(0);
        }

         /*
            F
         */
        try {
            entity.setSelectF(list.get(5).getOptions());

        }catch (IndexOutOfBoundsException e){
            entity.setSelectF(null);
        }

        try {
            entity.setWeightF(list.get(5).getWeight());

        }catch (IndexOutOfBoundsException e){
            entity.setWeightF(0);
        }

         /*
            G
         */
        try {
            entity.setSelectG(list.get(6).getOptions());

        }catch (IndexOutOfBoundsException e){
            entity.setSelectG(null);
        }

        try {
            entity.setWeightG(list.get(6).getWeight());

        }catch (IndexOutOfBoundsException e){
            entity.setWeightG(0);
        }




    }


    /**
     * 更新排序
     * @param param
     * @return
     */
    @PostMapping("/updateSort")
    public  Result<String> updatetExamIndex(@RequestBody QuestionParam param)
    {
        if(tokenService.compareToken(param.tokenEntity.getValue()))
        {

           int upCode = examService.updateExam(param.entity);
           if(upCode==0)
           {
               return ResultUtils.getResults(Result.Status.ERROR,"操作失败");
           }

            return ResultUtils.getResults(Result.Status.SUCCESS,"操作失败");
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "登录过期");
    }
/*
    @PostMapping("/delete")
    public  Result<String> deletetExamIndex(@RequestBody QuestionParam param) {
        if (tokenService.compareToken(param.tokenEntity.getValue())) {
            int insert = QuestionParam.deleteByPrimaryKey(param.entity.getId());
            if (insert == 0) {
                return ResultUtils.getResults(Result.Status.ERROR, "删除失败");
            }
            return ResultUtils.getResults(Result.Status.SUCCESS, "操作成功");
        }
        return ResultUtils.getResults(Result.Status.OVERTIME, "登录过期");
    }*/

    /**
     * 预览试卷
     * @param param
     * @return
     */
    @PostMapping("/getExamView")
    public Result<HashMap<String,Object>> preViewExam(@RequestBody QuestionParam param)
    {


        HashMap<String,Object> map = new HashMap<>();
        if(tokenService.compareToken(param.tokenEntity.getValue())){

            Long examId = param.filter.getExamId();

            if(ObjectUtils.isBlank(examId))
            {
                return ResultUtils.getResults(Result.Status.ERROR, "问卷主键为空",null);
            }

            List<ExamQuestionFilter> examList = examService.query(param.filter);
            ExamIndex indices = examIndexService.selectByPrimaryKey(examId);
            List<Map<String,Object> >  exlist = new ArrayList<>();
            for (ExamQuestionFilter exam : examList) {
                HashMap<String,Object> mapexam = new HashMap<>();
                mapexam.put("examId",exam.getExamId());
                mapexam.put("questionId",exam.getId());

                mapexam.put("optionId",exam.getOptionId());
                mapexam.put("selectId",exam.getAnswer());
                mapexam.put("stem",exam.getStem());
                List<SelectOptionBean> selectList = Util.setSelectList(exam);
                mapexam.put("selectList",selectList);
                exlist.add(mapexam);
            }


            map.put("list",exlist);
            map.put("exam",indices);
            return ResultUtils.getResults(Result.Status.SUCCESS, "查询成功", map);

        }

        return ResultUtils.getResults(Result.Status.OVERTIME, "登录过期",map);

    }

    /**
     * 二类问卷的上传
     * @param file
     */
    @PostMapping("/uploadQuestion")
    public Result<HashMap<String,Object>> uploadQuestion(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "examId") Long examId)
    {
        if(file ==null)
        {

            return ResultUtils.getResults(Result.Status.ERROR, "上传失败，上传文件不能为空",null);
        }
        String fileName = file.getOriginalFilename();

        if(!fileName.matches("^.+\\.(?i)(xls)$")&&!fileName.matches("^.+\\.(?i)(xlsx)$")){
            return ResultUtils.getResults(Result.Status.ERROR, "上传失败，文件格式错误",null);
        }

        if(ObjectUtils.isBlank(examId))
        {
            return ResultUtils.getResults(Result.Status.ERROR, "上传失败，examId主键空值",null);
        }

        deleteRepeat(examId);


        int i = excelService.uploadExcel(file,examId);
        if(i!=0) {
            if (i == 1) {
                return ResultUtils.getResults(Result.Status.ERROR, "上传失败，表格数据为空", null);
            } else if (i == 2) {
                return ResultUtils.getResults(Result.Status.ERROR, "上传失败，表头格式不正确，请按照模板上传数据", null);
            }
        }

        return ResultUtils.getResults(Result.Status.SUCCESS,"上传成功",null);
    }

    /**
     * 删除重复数据
     * @param examId
     */
    private  void deleteRepeat(Long examId )
    {
        ExamQuestionFilter exfilter = new ExamQuestionFilter();
        exfilter.setExamId(examId);
        /**
         * 题干旧数据
         */
        List<ExamQuestionFilter> query = examService.query(exfilter);
        if (ObjectUtils.isNotBlank(query)) {
            int code = examService.insertLog(query);

            if (code == 0) {
                System.out.println("保存失败");
            }

            examService.deleteByPrimaryKey(examId);
        }
    }
}



class QuestionParam {
    public ExamQuestionEntity entity;
    public ExamQuestionFilter filter;
    public TokenEntity tokenEntity;

}